package com.xctech.iot.mqtt.sdk.core;

import com.xctech.iot.mqtt.sdk.config.MqttConfig;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <pre>
 * mqtt 抽象客户端
 * </pre>
 *
 * @author: feihu.liang
 * @since: 2024/4/11 14:10
 */
public abstract class MqttAbstractClient {

    @Autowired
    protected MqttConfig mqttConfig;

    protected static final Integer QOS = 1;
    private static final boolean AUTO_RECONNECT = true;
    private static final boolean CLEAN_SESSION = true;
    private static final int MQTT_VERSION = 4;

    /**
     * <pre>
     * 建立连接
     * </pre>
     *
     * @return void
     * @throws MqttException
     */
    protected abstract void connect() throws MqttException;

    /**
     * <pre>
     * 获取连接对象
     * </pre>
     *
     * @param
     * @return org.eclipse.paho.client.mqtt3.MqttConnectOptions
     */
    protected MqttConnectOptions getConnOptions() {
        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setUserName(mqttConfig.getUsername());
        connectOptions.setPassword(mqttConfig.getPassword().toCharArray());
        connectOptions.setConnectionTimeout(mqttConfig.getCompletionTimeout());
        connectOptions.setKeepAliveInterval(mqttConfig.getKeepAlive());
        //connectOptions.setAutomaticReconnect(AUTO_RECONNECT);
        connectOptions.setMqttVersion(MQTT_VERSION);
        connectOptions.setCleanSession(CLEAN_SESSION);
        return connectOptions;
    }

}
